package xyz.quanguanjia.masterboy.model;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.util.Log;
import android.widget.Toast;

import androidx.localbroadcastmanager.content.LocalBroadcastManager;

import com.google.gson.Gson;
import com.google.gson.internal.LinkedTreeMap;
import com.luck.picture.lib.utils.ToastUtils;

import java.util.HashMap;

import xyz.quanguanjia.masterboy.MBDApplication;
import xyz.quanguanjia.masterboy.MBDHttpClient;
import xyz.quanguanjia.masterboy.MBDModelResponse;
import xyz.quanguanjia.masterboy.MBDNotificationCenter;
import xyz.quanguanjia.masterboy.ServiceType;
import xyz.quanguanjia.masterboy.me.MBDEditInfoActivity;
import xyz.quanguanjia.masterboy.util.StringUtils;


public class MBDAccountInfoModel {
    private static final String PREF_NAME = "MyPreferences";
    private static final String KEY_ACCOUNT_INFO = "AccountInfo";

    private String userId;
    private String phoneNumber;
    private String realName;
    private String avatarUrl;
    private String weChatNumber;

    public String getUserId() {
        return userId;
    }

    public void setUserId(String userId) {
        this.userId = userId;
    }

    public String getPhoneNumber() {
        return phoneNumber;
    }

    public void setPhoneNumber(String phoneNumber) {
        this.phoneNumber = phoneNumber;
    }

    public String getRealName() {
        return realName;
    }

    public void setRealName(String realName) {
        this.realName = realName;
    }

    public String getAvatarUrl() {
        return avatarUrl;
    }

    public void setAvatarUrl(String avatarUrl) {
        this.avatarUrl = avatarUrl;
    }

    public String getWeChatNumber() {
        return weChatNumber;
    }

    public void setWeChatNumber(String weChatNumber) {
        this.weChatNumber = weChatNumber;
    }


    public static void fetch() {
        doGetUserInfoRequest(new MBDAccountInfoModel.RequestCallBack() {
            @Override
            public void completion(MBDAccountInfoModel accountInfoModel) {
                if (null != accountInfoModel) {
                    accountInfoModel.save();
                    saveDeviceToken(accountInfoModel.userId);
                    //通知
                    Intent intent = new Intent(MBDNotificationCenter.NOTIFICATION_UPDATE_USERINFO);
                    // 发送广播
                    LocalBroadcastManager.getInstance(MBDApplication.getContext()).sendBroadcast(intent);
                }

            }
        });
    }

    private static void saveDeviceToken(String userId) {
        if (!StringUtils.isNull(MBDApplication.deviceToken)) {
            HashMap<String, String> params = new HashMap<String, String>();
            params.put("deviceToken", MBDApplication.deviceToken);
            params.put("userId", userId);

            MBDHttpClient.shared().doRequest(ServiceType.SERVICE_USER_UPDATE_INFO, params, new MBDHttpClient.Callback() {
                @Override
                public void completion(boolean success, Error error, MBDModelResponse response) {
                    if (success) {
                        Log.d("TPush", "注册成功，设备token为：" + MBDApplication.deviceToken + "  USERID " + userId);
                    }
                }
            });
        }
    }

    public static void update(boolean notify) {
        if (notify) {
            fetch();
        } else {
            doGetUserInfoRequest(new MBDAccountInfoModel.RequestCallBack() {
                @Override
                public void completion(MBDAccountInfoModel accountInfoModel) {
                    if (null != accountInfoModel) {
                        accountInfoModel.save();
                    }
                }
            });
        }
    }

    public static MBDAccountInfoModel current() {
        SharedPreferences sharedPreferences = MBDApplication.getContext().getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE);
        ;
        Gson gson = new Gson();
        String json = sharedPreferences.getString(KEY_ACCOUNT_INFO, null);
        if (json != null) {
            return gson.fromJson(json, MBDAccountInfoModel.class);
        }
        return null;
    }

    private static void doGetUserInfoRequest(MBDAccountInfoModel.RequestCallBack callBack) {

        MBDHttpClient.shared().doRequest(ServiceType.SERVICE_USER_GET_INFO, null, new MBDHttpClient.Callback() {
            @Override
            public void completion(boolean success, Error error, MBDModelResponse response) {
                if (success) {
                    // TODO: 2024/10/22  
                    callBack.completion(convert2AccountInfoModel((LinkedTreeMap) response.data));
                } else {
                    callBack.completion(null);
                }
            }
        });
    }

    private void save() {
        Gson gson = new Gson();
        String json = gson.toJson(this);
        SharedPreferences sharedPreferences = MBDApplication.getContext().getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE);
        ;
        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.putString(KEY_ACCOUNT_INFO, json);
        editor.apply();
    }

    public static boolean clear() {
        SharedPreferences sharedPreferences = MBDApplication.getContext().getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE);
        ;
        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.putString(KEY_ACCOUNT_INFO, null);
        editor.apply();
        return true;
    }

    private static MBDAccountInfoModel convert2AccountInfoModel(LinkedTreeMap<String, Object> linkedTreeMap) {
        Gson gson = new Gson();
        String jsonString = gson.toJson(linkedTreeMap);
        return gson.fromJson(jsonString, MBDAccountInfoModel.class);
    }

    private interface RequestCallBack {
        public void completion(MBDAccountInfoModel accountInfoModel);

    }
}
